package org.ihelpuoo.weboo.module;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ihelpuoo.lang.ObjectUtils;
import org.ihelpuoo.orm.filter.FieldFilter;
import org.ihelpuoo.orm.filter.Filter;
import org.ihelpuoo.weboo.Weboo;
import org.ihelpuoo.weboo.util.HttpQuerySQLFilter;
import org.ihelpuoo.weboo.util.OutputType;

public class ActionContext extends AbstractContext
{
	protected ActionContext(ModuleContext mc, ActionConfig ac, HttpServletRequest request,
			HttpServletResponse response)
	{
		super(mc,request,response);
		this.ac = ac;
	}

	private ActionConfig		ac;
	private ActionProperties	_properties;

	public ActionConfig getActionConfig()
	{
		return ac;
	}

	public Object getFormObject()
	{
		return getFormObject(null,null);
	}

	public Object getFormObject(FieldFilter actived, FieldFilter locked)
	{
		try
		{
			Class type = properties().getObjectType();
			Object obj = ObjectUtils.newInstance(type);
			return pojo().fetch(request,obj,actived,locked);
		}
		catch (Exception e)
		{
		}
		return null;
	}

	public Object getReferObject()
	{
		try
		{
			Class type = properties().getAsClass(Weboo.REFER_TYPE);
			Object obj = ObjectUtils.newInstance(type);
			return pojo().fetch(request,obj);
		}
		catch (Exception e)
		{
		}
		return null;
	}

	public ActionProperties properties()
	{
		if (this._properties == null)
			this._properties = new ActionProperties(ac);
		return this._properties;
	}

	public Filter getObjectFilter()
	{
		try
		{
			String v = properties().getStringTrimed(Weboo.FILTER_TYPE);
			if("auto".equalsIgnoreCase(v))
			{
				HttpQuerySQLFilter filter =  new HttpQuerySQLFilter(this);
				filter.setCondition(properties().getStringTrimed("filter.condition"));
				filter.setOrderBy(properties().getStringTrimed("filter.orderby"));
				return filter;
			}
			Class type = Class.forName(v);
			Filter filter = (Filter)ObjectUtils.newInstance(type);
			return (Filter)pojo().fetch(request,filter);
		}
		catch (Exception e)
		{
		}
		return null;
	}

	public String getActionnName()
	{
		return ac.getName();
	}

	public OutputType getOutputType()
	{
		if (properties().contains("output.type"))
			return new OutputType(properties().getString("output.type"));
		return getWebooConfig().getActionOutputType();
	}
}
